<script setup lang='ts' name="label-add">
import { ArrowLeftBold, ArrowRightBold } from '@element-plus/icons-vue'
import { getCityLevelList } from '@fl/api/xf-api/label-manage'
import { addRankProject, getRankProject, updateRankProject } from '@fl/api/xf-api/xf-manage'
import { stat } from 'node:fs'
import { boolean } from 'zod'

const props = defineProps({
    row: Object,
    show: Boolean,
    title: String,
})

const emit = defineEmits(['close'])
const form = reactive({
    rankDayType: 0,
    rankType: 1,
    leftCityCode: '420100000000',
    rightCityCode: '420100000000',
    leftAreaCode: 'A01',
    leftAreaName: '全武汉',
    rightAreaCode: 'A01',
    rightAreaName: '全武汉',
})

const cityOptions = ref([
    {
        cityName: '武汉市',
        cityCode: '420100000000',
    },
])

// 筛选时间类型：0:昨日，1：7日，2：30日
const rankDayTypeOptions = ref([
    {
        label: '昨日',
        value: 0,
    },
    {
        label: '7日',
        value: 1,
    },
    {
        label: '30日',
        value: 2,
    },
])

// 排行类型：0：关注榜，1：人气榜
const rankTypeOptions = ref([
    {
        label: '人气榜',
        value: 1,
    },
    {
        label: '关注榜',
        value: 0,
    },
])

function switchState() {
    queryTagProject()
}

function switchDayState() {
    queryTagProject()
}

const xTable1Height = ref<number>(400)
const xTable2Height = ref<number>(400)
const loading = ref(true)
const areaName1 = ref('全武汉')
const projectName1 = ref('')

const areaName2 = ref('全武汉')
const projectName2 = ref('')
const districtTypes = ref([])

function getDistrictList() {
    getCityLevelList().then((res) => {
        // "id": 18, "code": "25011300000", "name": "东湖新技术开发区"
        const cityList = res.data
	    const targetCity = cityList.find((item) => {
            return item.areaName == '武汉市'
        })
        districtTypes.value = targetCity.children
        districtTypes.value.unshift({ areaName: '全武汉', areaCode: 'A01' })
    })
}

type projectItem = {
    areaName: string
    projectId: number | string
    projectName: string
}
const choseProjectList = ref([])
const rightProjectList = ref([])
const unChoseProjectList = ref([])
const choseProjects = ref([])
const unChoseProjects = ref([])
const rightValue = ref([])
const rightCheckedValue = ref([])
function queryTagProject() {
    const params = {
        addCityCode: '420100000000',
        addAreaCode: form.rightAreaCode === 'A01' ? undefined : form.rightAreaCode,
        addXmmc: '',
        cityCode: '420100000000',
        areaCode: form.leftAreaCode === 'A01' ? undefined : form.leftAreaCode,
        xmmc: '',
        rankType: form.rankType,
        rankDayType: form.rankDayType,
        existPageNum: 1,
        existPageSize: 10000,
        notPageNum: 1,
        notPageSize: 10000,
    }
    getRankProject(params).then((res) => {
        loading.value = false
        if (res.code === 200) {
            rightProjectList.value = res.data.existProjects.records || []
            choseProjectList.value = res.data.existProjects.records || []
            unChoseProjectList.value = res.data.notExistProjects.records || []
            choseProjects.value = res.data.existProjects.records || []
            unChoseProjects.value = res.data.notExistProjects.records || []
            if (choseProjectList.value.length > 0) {
                choseProjectList.value.forEach((item) => {
                    rightValue.value.push(item.id)
                })
                rightCheckedValue.value = rightValue.value
            }
            filterProject1(projectName1.value)
            filterProject2(projectName2.value)
        }
        else {
            loading.value = false
            ElMessage.error(res.msg)
        }
    })
}

function areaName1Change(areaCode) {
    const it = districtTypes.value.filter((item) => {
        return item.areaCode == areaCode
    })
    form.leftAreaName = it[0].areaName
    // filterProject1(projectName1.value)
    queryTagProject()
}

function areaName2Change(areaCode) {
    const it = districtTypes.value.filter((item) => {
        return item.areaCode == areaCode
    })
    form.rightAreaName = it[0].areaName
    // filterProject2(projectName2.value)
    queryTagProject()
}

function filterProject1(val) {
    if (val) {
        if (form.leftAreaName !== '全武汉') {
            unChoseProjects.value = unChoseProjectList.value.filter((item) => {
                return item?.areaId === form.leftAreaName && item.xmmc.includes(val)
            })
        }
        else {
            unChoseProjects.value = unChoseProjectList.value.filter((item) => {
                return item.xmmc.includes(val)
            })
        }
    }
    else {
        if (form.leftAreaName !== '全武汉') {
            unChoseProjects.value = unChoseProjectList.value.filter((item) => {
                return item?.areaId === form.leftAreaName
            })
        }
        else {
            unChoseProjects.value = unChoseProjectList.value
        }
    }
}

function filterProject2(val) {
    if (val) {
        if (form.rightAreaName !== '全武汉') {
            choseProjectList.value = rightProjectList.value.filter((item) => {
                return item?.areaId === form.rightAreaName && item.xmmc.includes(val)
            })
        }
        else {
            choseProjectList.value = rightProjectList.value.filter((item) => {
                return item.xmmc.includes(val)
            })
        }
    }
    else {
        if (form.rightAreaName !== '全武汉') {
            choseProjectList.value = rightProjectList.value.filter((item) => {
                return item?.areaId === form.rightAreaName
            })
        }
        else {
            choseProjectList.value = rightProjectList.value
        }
    }
}

const leftCheckData = ref([])
const rightCheckData = ref([])
const xTable1 = ref(null)
const xTable2 = ref(null)

function selectAllEvent1({ checked }) {
    const records = xTable1.value?.getCheckboxRecords()
    console.log(checked ? '所有勾选事件' : '所有取消事件', records)
    leftCheckData.value = records
}

function selectAllEvent2({ checked }) {
    const records = xTable2.value?.getCheckboxRecords()
    console.log(checked ? '所有勾选事件' : '所有取消事件', records)
    rightCheckData.value = records
}

function selectChangeEvent1({ checked }) {
    const records = xTable1.value?.getCheckboxRecords()
    console.log(checked ? '勾选事件' : '取消事件', records)
    leftCheckData.value = records
}

function selectChangeEvent2({ checked }) {
    const records = xTable2.value?.getCheckboxRecords()
    console.log(checked ? '勾选事件' : '取消事件', records)
    rightCheckData.value = records
}

function toRight() {
    ElMessageBox.confirm(
        `是否确认将选中的${leftCheckData.value.length}个楼盘选中为当前排行下`,
        '系统提示',
        {
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            type: 'warning',
        },
    )
        .then(() => {
            projectName2.value = ''
            filterProject2('')
            choseProjects.value = choseProjects.value.concat(leftCheckData.value)
            let temArray = unChoseProjects.value
            leftCheckData.value.forEach(((item) => {
                temArray = temArray.filter((it) => {
                    return it.id !== item.id
                })
                console.log(temArray)
            }))

            // state 0:删除，1添加
            unChoseProjects.value = temArray
            unChoseProjectList.value = temArray
            saveTagProject(1)
            leftCheckData.value = []
        }).catch(() => {
            ElMessage({
                message: '您取消了操作',
                type: 'info',
            })
        })
}

function toLeft() {
    ElMessageBox.confirm(
        `是否确认将选中的${rightCheckData.value.length}个楼盘取消当前榜单下`,
        '系统提示',
        {
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            type: 'warning',
        },
    ).then(() => {
        projectName1.value = ''
        unChoseProjects.value = unChoseProjects.value.concat(rightCheckData.value)
        let temArray = choseProjects.value
        rightCheckData.value.forEach(((item) => {
            temArray = temArray.filter((it) => {
                return it.id !== item.id
            })
            console.log(temArray)
        }))
        choseProjects.value = rightCheckData.value
        saveTagProject(0)
        choseProjectList.value = temArray
        rightCheckData.value = []
    },
    ).catch(() => {
        ElMessage({
            message: '您取消了操作',
            type: 'info',
        })
    })
}

// 标签关联楼盘
async function saveTagProject(state) {
    const projectList = []
    if (state === 1) {
        if (leftCheckData.value.length > 0) {
            leftCheckData.value.forEach((it) => {
                const item = { projectName: it.xmmc, projectId: it.id }
                projectList.push(item)
            })
        }
    }
    else {
        if (choseProjects.value.length > 0) {
            choseProjects.value.forEach((it) => {
                const item = { projectName: it.xmmc, projectId: it.id }
                projectList.push(item)
            })
        }
    }

    const params = {
        chooseProject: projectList,
        state, // 0 删除  1是添加
        cityCode: '420100000000',
        cityName: '武汉市',
        areaCode: state === 1 ? (form.rightAreaCode === 'A01' ? undefined : form.rightAreaCode) : (form.leftAreaCode === 'A01' ? undefined : form.leftAreaCode),
        areaName: state === 1 ? (form.rightAreaCode === 'A01' ? undefined : form.rightAreaName) : (form.leftAreaCode === 'A01' ? undefined : form.leftAreaName),
        rankDayType: form.rankDayType,
        rankType: form.rankType,
    }

    const result = await addRankProject(params)
    if (result.code === 200) {
        ElMessage.success('操作成功')
        projectName1.value = ''
        projectName2.value = ''
        queryTagProject()
    }
    else {
        ElMessage.warning(result.msg)
    }
}

function closeTagProject() {
    rightProjectList.value = []
    choseProjectList.value = []
    unChoseProjectList.value = []
    choseProjects.value = []
    emit('close')
}

async function recoverHouse() {
    const params = {
        tagId: props.row?.tagId,
        tagType: props.row?.tagType,
    }
    const result = await restoreHouse(params)
    if (result.code === 200) {
        ElMessage.success('操作成功')
        projectName1.value = ''
        projectName2.value = ''
        queryTagProject()
    }
    else {
        ElMessage.warning(result.msg)
    }
}

onMounted(() => {
    getDistrictList()
    if (props) {
        queryTagProject()
    }
})

onUnmounted(() => {
    unChoseProjectList.value = []
    choseProjectList.value = []
    unChoseProjects.value = []
    choseProjects.value = []
})
const dialogVisible = ref(false)
watch(props, (newValue, oldValue) => {
    dialogVisible.value = newValue.show
}, {
    deep: true,
    immediate: true,
})
</script>

<template>
    <el-dialog v-model="dialogVisible"
               :title="props.title"
               width="80%"
               draggable
               @close="closeTagProject"
    >
        <el-form :validate-on-rule-change="false"
                 :model="form"
                 class="area-select"
        >
            <el-row style="width:100%">
                <el-col :span="24">
                    <el-form-item label="榜单类型"
                                  prop="state"
                    >
                        <el-radio-group v-model="form.rankType"
                                        @change="switchState"
                        >
                            <el-radio v-for="item in rankTypeOptions"
                                      :key="item.value"
                                      :label="item.value"
                            >
                                {{ item.label }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>

                <el-col :span="24">
                    <el-form-item label="时间类型"
                                  prop="state"
                    >
                        <el-radio-group v-model="form.rankDayType"
                                        @change="switchDayState"
                        >
                            <el-radio v-for="item in rankDayTypeOptions"
                                      :key="item.value"
                                      :label="item.value"
                            >
                                {{ item.label }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>

                <el-col :span="10">
                    <div class="card-header"
                         style="display: flex;"
                    >
                        未选中楼盘(<span>{{ unChoseProjects.length }}</span>)
                    </div>

                    <el-row style="margin-top:4px;">
                        <el-input v-model="projectName1"
                                  placeholder="请输入楼盘名称"
                                  :prefix-icon="Search"
                                  @input="filterProject1"
                                  @change="filterProject1"
                        >
                            <template #prepend>
                                <el-select v-model="form.leftCityCode"
                                           style="width: 115px;background-color: #fff;"
                                           @change="areaName2Change"
                                >
                                    <el-option v-for="(it, index) in cityOptions"
                                               :key="index"
                                               :label="it.cityName"
                                               :value="it.cityCode"
                                    />
                                </el-select>

                                <el-select v-model="form.leftAreaCode"
                                           placeholder="选择区域"
                                           style="width: 115px;background-color: #fff;"
                                           @change="areaName1Change"
                                >
                                    <el-option v-for="(it, index) in districtTypes"
                                               :key="index"
                                               :label="it.areaName"
                                               :value="it.areaCode"
                                    />
                                </el-select>
                            </template>
                        </el-input>
                    </el-row>

                    <div style="height: 400px">
                        <el-scrollbar>
                            <vxe-table ref="xTable1"
                                       :data="unChoseProjects"
                                       :height="xTable1Height"
                                       :show-header="true"
                                       stripe
                                       :loading="loading"
                                       :row-config="{ isHover: true }"
                                       :tooltip-config="{ zIndex: 9999 }"
                                       @checkbox-all="selectAllEvent1"
                                       @checkbox-change="selectChangeEvent1"
                            >
                                <vxe-column type="checkbox"
                                            width="40"
                                />
                                <!-- title="全选" -->

                                <vxe-column type="xmmc"
                                            field="xmmc"
                                            title="楼盘名称"
                                            :min-width="100"
                                            show-overflow
                                />

                                <vxe-column type="areaId"
                                            field="areaId"
                                            title="所在区域"
                                            show-overflow
                                />
                            </vxe-table>
                        </el-scrollbar>
                    </div>
                </el-col>

                <el-col :span="4"
                        style="display: flex;align-items: center;justify-content: center;"
                >
                    <el-button type="primary"
                               :icon="ArrowLeftBold"
                               :disabled="rightCheckData.length === 0"
                               style="margin-right:10px"
                               @click="toLeft"
                    />

                    <el-button type="primary"
                               :icon="ArrowRightBold"
                               :disabled="leftCheckData.length === 0"
                               @click="toRight"
                    />
                </el-col>

                <el-col :span="10">
                    <div class="card-header"
                         style="display: flex;"
                    >
                        已选中楼盘(<span>{{ choseProjectList.length }}</span>)
                    </div>

                    <el-row style="margin-top:4px;">
                        <el-input v-model="projectName2"
                                  placeholder="请输入楼盘名称"
                                  :prefix-icon="Search"
                                  @input="filterProject2"
                        >
                            <template #prepend>
                                <el-select v-model="form.rightCityCode"
                                           placeholder="选择城市"
                                           style="width: 115px;background-color: #fff;"
                                           @change="cityCode"
                                >
                                    <el-option v-for="(it, index) in cityOptions"
                                               :key="index"
                                               :label="it.cityName"
                                               :value="it.cityCode"
                                    />
                                </el-select>

                                <el-select v-model="form.rightAreaCode"
                                           placeholder="选择区域"
                                           style="width: 115px;background-color: #fff;"
                                           @change="areaName2Change"
                                >
                                    <el-option v-for="(it, index) in districtTypes"
                                               :key="index"
                                               :label="it.areaName"
                                               :value="it.areaCode"
                                    />
                                </el-select>
                            </template>
                        </el-input>
                    </el-row>

                    <div style="height: auto">
                        <el-scrollbar>
                            <vxe-table ref="xTable2"
                                       :data="choseProjectList"
                                       :loading="loading"
                                       :height="xTable2Height"
                                       :show-header="true"
                                       :tooltip-config="{ zIndex: 9999 }"
                                       stripe
                                       @checkbox-all="selectAllEvent2"
                                       @checkbox-change="selectChangeEvent2"
                            >
                                <vxe-column type="checkbox"
                                            width="40"
                                />
                                <!-- title="全选" -->
                                <vxe-column type="xmmc"
                                            field="xmmc"
                                            title="楼盘名称"
                                            :min-width="100"
                                            show-overflow
                                />

                                <vxe-column type="areaId"
                                            field="areaId"
                                            title="所在区域"
                                            show-overflow
                                />
                            </vxe-table>
                        </el-scrollbar>
                    </div>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <span class="dialog-footer">

                <!-- <el-button v-if="props.row.state === 0"
                           type="primary"
                           @click="recoverHouse"
                >
                    恢复上次数据
                </el-button>
                -->
                <el-button @click="closeTagProject">
                    取消
                </el-button>

                <el-button type="primary"
                           @click="closeTagProject"
                >
                    关闭
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
  :deep() {
    --vxe-primary-color: #da0004;
    --vxe-loading-color: #da0004;
}

:deep(.vxe-table--render-default .vxe-body--row.row--stripe) {
    background-color: #fff !important;
}
</style>
